<template>
  <div>
    <base-modal
      :title="$t('member.components.title44')"
      :show.sync="visible"
      width="700px"
      :close-on-click-modal="false"
      @cancel="close"
    >
      <div class="recharge-dialog">
        <div class="recharge">
          {{$t('member.components.title15')}}<el-input class="recharge-number" v-model="chargeNum" @blur="changeChargeNum" :placeholder="$t('common.placeholder.input2')"></el-input>{{$t('common.member.serviceFee')}}, 
          {{$t('member.components.title50')}}<TimePickRange class="time-pick-wrap" :date-unit="dateUnit" :expire-date="expireDate" :rule-type="ruleType" @updateTime="updateTime"/>
          <el-button type="primary" @click="handleConfirm">{{$t('member.components.title15')}}</el-button>
        </div>
        <el-table
          stripe
          v-loading="listLoading"
          :data="list"
          :highlight-current-row="false"
          border
          class="point-table"
          ref="multipleTable"
        >
          <template slot="empty">
            <BaseListForNoData
              v-show="!listLoading"
              :notice-msg="$t('common.base.noData')"
            ></BaseListForNoData>
          </template>
          <template v-for="(column, index) in serviceFeeRechargeFields">
            <el-table-column
              :key="`${column.field}_${index}`"
              :label="column.label"
              :prop="column.field"
              :min-width="column.minWidth || '120px'"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <template v-if="column.field === 'action'">
                  <el-button type="text" @click="cancelRecord(scope.row)">{{$t('member.components.title14')}}</el-button>
                </template>
                <template v-else-if="column.field === 'validityPeriod'">
                  {{ scope.row.startTime | fmt_form_date }} {{$t('common.base.to')}} {{ scope.row.endTime  | fmt_form_date }} 
                </template>
                <template v-else-if="column.field === 'createTime'">
                  {{ scope.row.createTime | fmt_form_date }} 
                </template>
                <template v-else>
                  <div>
                    {{ scope.row[column.field] }}
                  </div>
                </template>
              </template>
            </el-table-column>
          </template>
        </el-table>
        <el-pagination
          class="product-table-pagination"
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[10, 20, 50]"
          :page-size="page.pageSize"
          :current-page="page.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="totalElements"
        >
        </el-pagination>
      </div>
    </base-modal>
  </div>
</template>

<script>
import { serviceFeeRechargeFields } from '@src/modules/member/field.js';
import TimePickRange from './TimePickRange.vue';
import { getMemberConfig, searchServiceFeeRecharge, memberRecharge, memberObsolete } from '@src/api/Member'
import dayjs from 'dayjs';
import MathUtil from '@src/util/math';
const dateUnitArr = ['year', 'month', 'day']
export default {
  name: 'recharge-dialog',
  components: {
    TimePickRange
  },
  data() {
    return {
      visible: false,
      type: '',
      chargeNum: '',
      chargeType: '',
      listLoading: false,
      list: [],
      memberServiceFeeRule: {},
      serviceFeeRechargeFields,
      effectTime: [],
      membershipId: '',
      page: {
        pageSize: 10,
        pageNum: 1,
      },
      totalElements: 0
    };
  },
  computed: {
    expireDate() {
      return this.memberServiceFeeRule.expireDate 
    },
    ruleType() {
      return this.memberServiceFeeRule.ruleType 
    },
    dateUnit() {
      let settingUnit = Number(this.memberServiceFeeRule.dateUnit)
      return dateUnitArr[settingUnit-1]
    },
  },
  mounted() {
    this.getMemberConfig()
  },
  methods: {
    close() {
      this.chargeNum = ''
      if(this.pointRule.ruleType != 3) {
        this.effectTime = []
      }
      this.$eventBus.$emit('closeDialog');
    },
    handleCurrentChange(pageNum) {
      this.page.pageNum = pageNum;
      this.getServiceFeeTableData();
    },
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.page.pageNum = 1;
      this.getServiceFeeTableData();
    },
    async getMemberConfig() {
      const { status, data } = await getMemberConfig();
      if (status !== 0) return this.$message.error(this.$t('member.components.title49'));
      this.memberServiceFeeRule = data.memberServiceFee.rule
      if(this.memberServiceFeeRule.ruleType == 3) {
        let startTime = dayjs().valueOf()
        let endTime = dayjs('2999-12-31 23:59:59').valueOf()
        this.effectTime = [startTime,endTime]
      }
    },
    open(row, type) {
      this.chargeType = type 
      // 获取表格数据
      this.membershipId = row.id
      this.getServiceFeeTableData()
      this.visible = true
    },
    async getServiceFeeTableData() {
      this.listLoading = true
      let params = {
        notExpired: true,
        notObsolete: true,
        haveAvailable: true,
        membershipId: this.membershipId
      }
      const { code, result } = await searchServiceFeeRecharge(params);
      this.listLoading = false
      if (code !== 0) return this.$message.error(this.$t('member.components.title23'));
      this.list = result.list
    },
    changeChargeNum() {
      let message = this.validateNum()
      if(message) return this.$message.error(message)
    },
    validateNum() {
      let count = MathUtil.decimalNumber(this.chargeNum);
      let message = ''
      if (!this.chargeNum) {
        message = this.$t('member.components.title24')
      } else if (this.chargeNum >= 1000000 || this.chargeNum < 0 || count > 0) {
        message = this.$t('member.components.title10')
      }
      return message
    },
    async handleConfirm() {
      let message = this.validateNum()
      if(message) return this.$message.error(message)
      if(!this.effectTime.length) return this.$message.error(this.$t('member.components.title25'))

      // 调用充值接口
      if(this.chargeNum && this.effectTime.length) {
        let params = {
          membershipId: this.membershipId,
          propertyType: 3,
          num: this.chargeNum,
          startTime: this.effectTime[0],
          endTime: this.effectTime[1]
        }
        const { code, result } = await memberRecharge(params);
        if (code !== 0) return this.$message.error(this.$t('member.components.title26'));
        this.$message.success(this.$t('member.components.title27'));
        this.close()
        this.getServiceFeeTableData()
        this.updateList()
      }
    },
    updateList() {
      this.$emit('updateList')
    },
    updateTime(time) {
      this.effectTime = time
    },
    async cancelRecord(item) {
      const result = await this.$platform.confirm(this.$t('member.components.title28'));
      if (!result) return 
      this.deleteRecord(item)
    },
    async deleteRecord(val) {
      // 删除接口调用
      let params = {
        memberRechargeId: val.id
      }
      const { code, result } = await memberObsolete(params);
      if (code !== 0) return this.$message.error(this.$t('member.components.title29'));
      this.$message.success(this.$t('member.components.title30'));
      this.close()
      this.getServiceFeeTableData()
      this.updateList()
    }
  },
};
</script>

<style lang="scss" scoped>
.recharge-dialog {
  padding: 20px;
  .recharge {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    .recharge-number {
      width: 20%;
      margin-left: 5px;
    }
    .time-pick-wrap {
      flex: 1;
      min-width: 45%;
    }
  }
  .point-table {
    margin: 20px 0 20px 0
  }
}
</style>
